<?php
/**
 * Created by PhpStorm.
 * User: cc
 * Date: 2023/7/27
 * Time: 3:06 PM
 */

namespace app\api\controller\v40;

use app\aliyun\controller\AliyunFilterWord;
use app\api\controller\v2\Auth;
use app\chat\LiveMessage;
use app\common\cachemodel\AppConfig;
use app\common\cachemodel\zlcr3\Zlcr3ConsultAccount;
use app\common\cachemodel\zlcr3\Zlcr3ConsultAccountReport;
use app\common\cachemodel\zlcr3\Zlcr3ConsultAstrData;
use app\common\cachemodel\zlcr3\Zlcr3ConsultChatRecord;
use app\common\cachemodel\zlcr3\Zlcr3ConsultChatRecordDetails;
use app\common\cachemodel\zlcr3\Zlcr3ConsultChatRtcRecord;
use app\common\cachemodel\zlcr3\Zlcr3ConsultChatRtcRecordComment;
use app\common\cachemodel\zlcr3\Zlcr3ConsultChatRtcRecordFeedback;
use app\common\cachemodel\zlcr3\Zlcr3Follow;
use app\common\cachemodel\ZlcrAstr;
use app\common\cachemodel\ZlcrTag;
use think\Db;
use think\response\Json;
use XznsTools\cache\CacheManage;

class ConsultInfo extends Auth
{
    /**
     * 关注取消关注
     * @return \think\response\Json
     * @throws \Exception
     */
    public function follow()
    {
        $type = input('type/d', 0);
        $astrId = input('astr_id/d', 0);

        $astrInfo = (new ZlcrAstr())->getInfoById($astrId, ['tel']);
        if (!$astrInfo)
        {
            return show(config('code.success'), 'Success.');
        }
        $followModel = new Zlcr3Follow();
        $followIdsIni = $followIds = $followModel->userFollowInfo(1, $this->user['id']);
        $followIds = $followIds ?: [];
        //关注
        if ($type === 1)
        {
            $followIds[] = $astrId;
        }//取消关注
        elseif ($followIds)
        {
            $remove = [$astrId];
            $followIds = array_diff($followIds, $remove);
        }
        if ($followIdsIni === null)
        {
            (new Zlcr3Follow())->insert(['type' => 1, 'uid' => $this->user['id'], 'follow_ids' => $followIds ? implode(',', $followIds) : '', 'create_time' => $this->request->time()]);
        } else
        {
            (new Zlcr3Follow())->where(['type' => 1, 'uid' => $this->user['id']])->update(['follow_ids' => $followIds ? implode(',', $followIds) : '', 'update_time' => $this->request->time()]);
            CacheManage::getInstance()->setCacheConfig($followModel->cacheModel, $this->user['id'])->setListKeyType(1)->rmCache();
        }
        return show(config('code.success'), 'Success.');
    }

    /**
     * 获取评价标签
     * @return Json
     * @throws \Exception
     */
    public function getCommentTag()
    {
        $tagModel = new ZlcrTag();
        $tag = $tagModel->getLevelTag(9, 0);
        $tag = $tagModel->getQuestionAllsResrt($tag);

        return show(config('code.success'), '请求成功', $tag);
    }

    /**
     * 咨询评价
     * @return \think\response\Json|void
     * @throws \Exception
     */
    public function comment()
    {
        $chatDetailId = input('id/d', 0);
        $tid = input('tid/d', 0);
        $remark = input('remark/s', '');
        if (!$chatDetailId || !$tid)
        {
            return show(config('code.error'), '请求异常，请稍后再试～');
        }
        if (empty($remark))
        {
            return show(config('code.error'), '评价原因不能为空');
        }
        if (mb_strlen($remark) > 60)
        {
            return show(config('code.error'), '评价原因最多60字');
        }
        $res = AliyunFilterWord::checkText($remark, 'article_comment');
        //若内容有违规且超过配置的相似比例，则进行隐藏不显示，将标签存入库中
        if ($res)
        {
            return show(0, '评价内容涉嫌' . $res['label']);
        }
        $zlcr3ConsultChatRecordDetailsModel = new Zlcr3ConsultChatRecordDetails();
        $zlcr3ConsultChatRtcRecordModel = new Zlcr3ConsultChatRtcRecord();
        $nowTimw = $this->request->time();
        $chatDetail = $zlcr3ConsultChatRecordDetailsModel->getInfoById($chatDetailId);
        $rtcId = $chatDetail['extend']['rtc_data']['rtc_id'] ?? 0;
        if (!$chatDetail || $chatDetail['uid'] !== $this->user['id'] || !$rtcId)
        {
            return show(config('code.error'), '咨询信息不存在，评价失败～');
        }
        //个咨询只能评价一次
        $rtcInfo = $zlcr3ConsultChatRtcRecordModel->getInfoById($rtcId);
        if (isset($rtcInfo['is_comment']) && $rtcInfo['is_comment'] > 0)
        {
            return show(config('code.error'), '已经评价过了，请勿重复操作～');
        }
        $tagInfo = (new ZlcrTag())->getInfoById($tid);
        if (!$tagInfo)
        {
            return show(config('code.error'), '请求异常，请稍后再试～');
        }
        if ($rtcInfo['status'] !== 4)
        {
            return show(config('code.error'), '咨询状态异常，评价失败');
        }
        // 写入 评价数据
        (new Zlcr3ConsultChatRtcRecordComment())->saveData([
            'rtc_id' => $rtcId,
            'uid' => $this->user['id'],
            'astr_id' => $rtcInfo['astr_id'],
            'level' => $tagInfo['flag'],
            'tid' => $tid,
            'comment' => $remark,
            'comment_type' => 1,
            'create_time' => $nowTimw
        ]);

        // 更新了评价状态
        $zlcr3ConsultChatRtcRecordModel->updateData($rtcInfo['id'], $rtcInfo['uid'], ['is_comment' => 1], 1);
        if ($tagInfo['flag'] !== 3)
        {   // 记录 好评与差评
            $fields = $tagInfo['flag'] > 3 ? 'level5_comment' : 'level1_comment';
            (new Zlcr3ConsultAstrData())->analysisDataUpdate($rtcInfo['astr_id'], (int)date('YmdH'), [
                $fields => Db::raw("{$fields} + 1")
            ]);
        }
        // 向咨询师 发送信息
        $consultChatRecordDetailsModel = new Zlcr3ConsultChatRecordDetails();
        $astrData = current($consultChatRecordDetailsModel->astrDataListResert([$chatDetail], [], $this->user));
        $astrData['is_comment'] = 1;    // 已评价
        LiveMessage::sendMsg(LiveMessage::who(LiveMessage::WHO_TYPE_ASTRO, 0, $rtcInfo['astr_id']), LiveMessage::MSG_TYPE_POP_CONSULT_MSG, [
            'msg_type' => 2,
            'uid' => $this->user['id'],
            'msg_data' => $astrData
        ]);
        //  4星和5星处理 咨询师给用户回消息
        if ($tagInfo['flag'] > 3)
        {
            $zlcr3ConsultChatRecordModel = new Zlcr3ConsultChatRecord();
            $chatId = $zlcr3ConsultChatRecordModel->getChatIdByAstrId($this->user['id'], $rtcInfo['astr_id']);
            if (!$chatId)
            {
                $insertData = [
                    'uid' => $this->user['id'],
                    'astr_id' => $rtcInfo['astr_id'],
                    'last_chat_detail_id' => 0,
                    'last_chat_detail_time' => 0,
                    'create_time' => $nowTimw,
                ];
                // 创建新的会话
                $chatId = $zlcr3ConsultChatRecordModel->SaveData($insertData);
            }
            $consultMsgData = [
                'chat_id' => $chatId,
                'uid' => $this->user['id'],
                'astr_id' => $rtcInfo['astr_id'],
                'type' => 1,    //  1=>APP消息 2=>用户发送消息
                'title' => '',
                'content' => '感谢你的评价及推荐！我会继续努力～', // 提问问题
                'data_type' => 1,   // 1=>普通消息  2=>图片  3=>语音咨询消息
                'extend' => [],  //  语音咨询消息 ｜ 图片信息
                'pid' => 0, // 待更新
                'create_time' => $nowTimw,
            ];
            $resData = $consultChatRecordDetailsModel->SaveData($chatId, $consultMsgData);
            $astrInfo = (new ZlcrAstr())->getInfoById($rtcInfo['astr_id']);
            $userData = current($consultChatRecordDetailsModel->userDataListResert([$resData], $astrInfo, $this->user));
            LiveMessage::sendMsg(LiveMessage::who(LiveMessage::WHO_TYPE_UID, 0, $this->user['id']), LiveMessage::MSG_TYPE_POP_CONSULT_MSG, [
                'msg_type' => 1,
                'astr_id' => $astrInfo['id'],
                'msg_data' => $userData
            ]);
            $astrData2 = current($consultChatRecordDetailsModel->astrDataListResert([$resData], $astrInfo, $this->user));
            LiveMessage::sendMsg(LiveMessage::who(LiveMessage::WHO_TYPE_ASTRO, 0, $rtcInfo['astr_id']), LiveMessage::MSG_TYPE_POP_CONSULT_MSG, [
                'msg_type' => 2,
                'uid' => $this->user['id'],
                'msg_data' => $astrData2
            ]);
            // 更新用户端 最后咨询信息
            $zlcr3ConsultChatRecordModel->updateData($chatId, [
                'last_chat_detail_id' => $chatDetailId,
                'last_chat_detail_time' => $nowTimw,
                'msg_num' => Db::raw('msg_num + 1')
            ]);
            // 未读数 +1
            $zlcr3ConsultChatRecordModel->setUserUnreadChatIdMsgNum($this->user['id'], $chatId, 1, 1);
        }
        return show(config('code.success'), 'Success');
    }

    /**
     * 连线咨询 推荐占星师
     * @return Json
     * @throws \Exception
     */
    public function recommend()
    {
        $chatDetailId = input('id/d', 0);
        $type = input('type/d', 0);

        if (!$chatDetailId || !in_array($type, [1, 2], true))
        {
            return show(config('code.error'), '请求异常，请稍后再试～');
        }
        $zlcr3ConsultChatRecordDetailsModel = new Zlcr3ConsultChatRecordDetails();
        $zlcr3ConsultChatRtcRecordModel = new Zlcr3ConsultChatRtcRecord();

        $chatDetail = $zlcr3ConsultChatRecordDetailsModel->getInfoById($chatDetailId);
        $rtcId = $chatDetail['extend']['rtc_data']['rtc_id'] ?? 0;
        if (!$chatDetail || $chatDetail['uid'] !== $this->user['id'] || !$rtcId)
        {
            return show(config('code.error'), '咨询信息不存在，推荐失败～');
        }
        $rtcInfo = $zlcr3ConsultChatRtcRecordModel->getInfoById($rtcId);
        if ($rtcInfo['status'] !== 4)
        {
            return show(config('code.error'), '咨询状态异常，推荐失败～');
        }
        if ($rtcInfo['is_recommend'] === 1)
        {
            return show(config('code.success'), '操作成功');
        }

        // 更新了评价状态
        $zlcr3ConsultChatRtcRecordModel->updateData($rtcInfo['id'], $rtcInfo['uid'], ['is_recommend' => $type], 1);

        if ($type === 1)
        {
            (new Zlcr3ConsultAccount())->updateData($rtcInfo['astr_id'], [   // 推荐次数 +1
                'recommended_nums' => Db::raw('recommended_nums + 1')
            ]);
            (new Zlcr3ConsultAstrData())->analysisDataUpdate($rtcInfo['astr_id'], (int)date('YmdH'), [
                'recommend_num' => Db::raw('recommend_num + 1')
            ]);
        }

        return show(config('code.success'), '操作成功');
    }

    /**
     * 我的咨询列表
     * @return Json
     * @throws \Exception
     */
    public function rtcChatList()
    {
        $data = (new Zlcr3ConsultChatRtcRecord())->userRtcChat($this->user['id']);
        return show(config('code.success'), '请求成功', $data);
    }

    /**
     * 咨询详情
     * @return Json
     * @throws \Exception
     */
    public function rtcChatDetail()
    {
        $chatDetailId = input('id/d', 0);
        $type = input('type/d', 0);//1=>完整 2=>精简【弹窗评价页面进入】
        $zlcr3ConsultChatRecordDetailsModel = new Zlcr3ConsultChatRecordDetails();

        $chatDetail = $zlcr3ConsultChatRecordDetailsModel->getInfoById($chatDetailId);
        $rtcId = $chatDetail['extend']['rtc_data']['rtc_id'] ?? 0;
        if (!$chatDetail || $chatDetail['uid'] !== $this->user['id'] || !$rtcId)
        {
            return show(config('code.error'), '服务异常，咨询信息不存在～');
        }
        $data = (new Zlcr3ConsultChatRtcRecord)->getInfoById($rtcId);

        $astrInfos = (new ZlcrAstr())->getInfoById($data['astr_id'], ['nickname', 'avatar']);
        $consultInfo = (new Zlcr3ConsultAccount())->getInfoById($data['astr_id'], ['price']);

        if ($type === 1)
        {
            $comment = $data['is_comment'] ? (new Zlcr3ConsultChatRtcRecordComment())->getInfoById($data['id'], ['level']) : null;

            $res = [
                'title' => '本次消耗详情',
                'list' => [
                    [
                        'title' => '服务编号',
                        'des' => $data['chat_detail_id'] ?? 0,
                        'type' => 2
                    ],
                    [
                        'title' => '申请时间',
                        'des' => date('Y-m-d H:i:s', $data['create_time']),
                        'type' => 1
                    ],
                    [
                        'title' => '咨询师',
                        'des' => $astrInfos['nickname'],
                        'type' => 1
                    ],
                    [
                        'title' => '咨询师单价',
                        'des' => $consultInfo['price'] . '准币/分钟',
                        'type' => 1
                    ],
                    [
                        'title' => '连线时长',
                        'des' => gmdate("H:i:s", $data['duration']),
                        'type' => 1
                    ],
                    [
                        'title' => '计费时长',
                        'des' => ceil($data['eff_duration'] / 60) . '分钟',
                        'type' => 1
                    ],
                    [
                        'title' => '连线消耗',
                        'des' => $data['coin'] . '准币',
                        'type' => 1
                    ],
                    [
                        'title' => '评价',
                        'des' => $data['is_comment'] ? $comment['level'] : '前往评价',
                        'type' => $data['is_comment'] ? 3 : 4
                    ]
                ]
            ];
            if ($data['is_recommend'] === 1)
            {
                $res['list'][] = [
                    'title' => '推荐',
                    'des' => '已推荐',
                    'type' => 1
                ];
            }
        } else
        {
            $res = [
                'title' => '本次消耗详情',
                'list' => [
                    [
                        'title' => '服务编号',
                        'des' => $data['chat_detail_id'] ?? 0,
                        'type' => 2
                    ],
                    [
                        'title' => '咨询师单价',
                        'des' => $consultInfo['price'] . '准币/分钟',
                        'type' => 1
                    ],
                    [
                        'title' => '连线时长',
                        'des' => gmdate("H:i:s", $data['duration']),
                        'type' => 1
                    ],
                    [
                        'title' => '连线消耗',
                        'des' => $data['coin'] . '准币',
                        'type' => 1
                    ],
                ]
            ];
        }
        $res['nickname'] = $astrInfos['nickname'];
        $res['avatar'] = $astrInfos['avatar'];

        return show(config('code.success'), '请求成功', $res);
    }

    /**
     * 举报占星师
     * @return Json
     * @throws \Exception
     */
    public function reportAstr()
    {
        $astrId = input('astr_id/d', 0);
        $feedback = input('feedback/s', '');
        $tel = input('phone/s', '');
        if (!$feedback || mb_strlen($feedback) > 60)
        {
            return show(config('code.error'), '举报内容字数60字以内');
        }
        $astrInfo = (new ZlcrAstr())->getInfoById($astrId, ['nickname']);
        if (!$astrInfo)
        {
            return show(config('code.error'), '咨询师不存在');
        }
        (new Zlcr3ConsultAccountReport())->insert([
            'uid' => $this->user['id'],
            'astr_id' => $astrId,
            'tel' => $tel,
            'content' => $feedback,
            'create_time' => time()
        ]);
        return show(config('code.success'), '举报成功');
    }

    /**
     * 咨询记录反馈
     * @return Json
     * @throws \Exception
     */
    public function feedbackRtcChat()
    {
        $chatDetailId = input('id/d', 0);
        $feedback = input('feedback/s', '');
        $tel = input('phone/s', '');
        if (!$feedback || mb_strlen($feedback) > 60)
        {
            return show(config('code.error'), '反馈内容字数60字以内');
        }
        $chatDetail = (new Zlcr3ConsultChatRecordDetails())->getInfoById($chatDetailId);
        $rtcId = $chatDetail['extend']['rtc_data']['rtc_id'] ?? 0;
        if (!$chatDetail || $chatDetail['uid'] !== $this->user['id'] || !$rtcId)
        {
            return show(config('code.error'), '服务异常，咨询信息不存在～');
        }
        $rtcChat = (new Zlcr3ConsultChatRtcRecord)->getInfoById($rtcId);
        if (!$rtcChat || $rtcChat['uid'] !== $this->user['id'])
        {
            return show(config('code.error'), '反馈失败');
        }
        (new Zlcr3ConsultChatRtcRecordFeedback())->insert([
            'status' => 0,
            'uid' => $this->user['id'],
            'astr_id' => $rtcChat['astr_id'],
            'chat_detail_id' => $chatDetailId,
            'tel' => $tel,
            'feedback' => $feedback,
            'create_time' => time(),
        ]);
        return show(config('code.success'), '反馈完成');
    }

    /**
     * 定制_取在线接单咨询师列表
     * @return Json
     * @throws \Exception
     */
    public function customAstrList()
    {
        $astrModel = new ZlcrAstr();
        $workIds = $astrModel->astrIds(1);
        $taskIds = $astrModel->astrIds(2);
        $ids = array_values(array_diff($workIds, $taskIds));
        $testIds = (new AppConfig())->configInfo('rtc')['test_user'];
        $testIds = $testIds ? explode(',', $testIds) : [];
        $ids = array_values(array_diff($ids, $testIds));
        $infos = $astrModel->batchGetInfoByIds($ids, ['id', 'extend', 'nickname', 'avatar', 'answer_num', 'rating']);
        $res = [];
        foreach ($infos as $info)
        {
            $res[] = [
                'id' => $info['id'],
                'name' => $info['nickname'],
                'avatar' => $info['avatar'],
                'des' => $info['work_intro'],
                'tip' => $info['answer_num'] ? "服务过{$info['answer_num']}人·好评率{$info['rating']}" : ''
            ];
        }
        return show(config('code.success'), '', $res);
    }
}
